// 初始化图表
document.addEventListener('DOMContentLoaded', function () {
    // RFM总分趋势图
    const rfmTrendCtx = document.getElementById('rfmTrendChart').getContext('2d');
    const rfmTrendChart = new Chart(rfmTrendCtx, {
        type: 'line',
        data: {
            labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
            datasets: [{
                label: 'RFM总分平均值',
                data: [10.5, 11.2, 10.8, 11.5, 12.3, 12.8],
                borderColor: '#165DFF',
                backgroundColor: 'rgba(22, 93, 255, 0.1)',
                fill: true,
                tension: 0.4,
                borderWidth: 2,
                pointBackgroundColor: '#165DFF',
                pointRadius: 4,
                pointHoverRadius: 6
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            onHover: (event, chartElement) => {
                event.native.target.style.cursor = chartElement[0] ? 'pointer' : 'default';
            },
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    mode: 'index',
                    intersect: false,
                    backgroundColor: 'rgba(255, 255, 255, 0.9)',
                    titleColor: '#1D2129',
                    bodyColor: '#4E5969',
                    borderColor: 'rgba(22, 93, 255, 0.2)',
                    borderWidth: 1,
                    padding: 12,
                    boxPadding: 6,
                    usePointStyle: true,
                    callbacks: {
                        label: function (context) {
                            return `RFM总分: ${context.raw}`;
                        }
                    }
                }
            },
            scales: {
                x: {
                    grid: {
                        display: false
                    },
                    ticks: {
                        color: '#86909C'
                    }
                },
                y: {
                    beginAtZero: false,
                    min: 8,
                    max: 14,
                    grid: {
                        color: 'rgba(0, 0, 0, 0.05)'
                    },
                    ticks: {
                        color: '#86909C'
                    }
                }
            },
            interaction: {
                mode: 'nearest',
                axis: 'x',
                intersect: false
            }
        }
    });

    document.getElementById('rfmTrendChart').onclick = function (evt) {
        const points = rfmTrendChart.getElementsAtEventForMode(evt, 'nearest', { intersect: true }, true);
        if (points.length) {
            const firstPoint = points[0];
            const label = rfmTrendChart.data.labels[firstPoint.index];
            const value = rfmTrendChart.data.datasets[firstPoint.datasetIndex].data[firstPoint.index];
            showTrendDetail(label, value);
        }
    };

    // 客户RFM分布散点图
    const rfmScatterCtx = document.getElementById('rfmScatterChart').getContext('2d');
    const rfmScatterChart = new Chart(rfmScatterCtx, {
        type: 'scatter',
        data: {
            datasets: [
                {
                    label: '高价值客户',
                    data: [
                        { x: 5, y: 8500, r: 12 }, { x: 7, y: 7200, r: 10 }, { x: 3, y: 9100, r: 14 },
                        { x: 10, y: 6800, r: 9 }, { x: 8, y: 7900, r: 11 }, { x: 2, y: 9500, r: 15 },
                        { x: 6, y: 7500, r: 10 }, { x: 4, y: 8200, r: 12 }, { x: 9, y: 6500, r: 8 },
                        { x: 1, y: 9800, r: 16 }
                    ],
                    backgroundColor: 'rgba(22, 93, 255, 0.7)',
                    borderColor: '#165DFF',
                    borderWidth: 1
                },
                {
                    label: '普通客户',
                    data: [
                        { x: 15, y: 3200, r: 6 }, { x: 20, y: 2800, r: 5 }, { x: 12, y: 3600, r: 7 },
                        { x: 25, y: 2100, r: 4 }, { x: 18, y: 3000, r: 6 }, { x: 14, y: 3400, r: 7 },
                        { x: 22, y: 2500, r: 5 }, { x: 17, y: 3100, r: 6 }, { x: 28, y: 1900, r: 4 },
                        { x: 24, y: 2300, r: 5 }
                    ],
                    backgroundColor: 'rgba(209, 213, 219, 0.7)',
                    borderColor: '#D1D5DB',
                    borderWidth: 1
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    mode: 'index',
                    intersect: false,
                    backgroundColor: 'rgba(255, 255, 255, 0.9)',
                    titleColor: '#1D2129',
                    bodyColor: '#4E5969',
                    borderColor: 'rgba(22, 93, 255, 0.2)',
                    borderWidth: 1,
                    padding: 12,
                    boxPadding: 6,
                    usePointStyle: true,
                    callbacks: {
                        label: function (context) {
                            return [
                                `最近消费: ${context.parsed.x}天`,
                                `消费金额: ¥${context.parsed.y}`,
                                `消费频率: ${context.parsed.r}次/月`
                            ];
                        }
                    }
                }
            },
            scales: {
                x: {
                    type: 'linear',
                    position: 'bottom',
                    title: { display: true, text: '最近消费天数(R)', color: '#86909C', font: { size: 12 } },
                    grid: { color: 'rgba(0, 0, 0, 0.05)' },
                    ticks: { color: '#86909C' }
                },
                y: {
                    type: 'linear',
                    title: { display: true, text: '消费金额(M)', color: '#86909C', font: { size: 12 } },
                    grid: { color: 'rgba(0, 0, 0, 0.05)' },
                    ticks: { color: '#86909C', callback: function (value) { return '¥' + value; } }
                }
            }
        }
    });

    // 客户类型占比饼图
    const customerTypeCtx = document.getElementById('customerTypeChart').getContext('2d');
    const customerTypeChart = new Chart(customerTypeCtx, {
        type: 'doughnut',
        data: {
            labels: ['重要价值客户', '重要保持客户', '重要发展客户', '重要挽留客户', '一般价值客户', '低价值客户'],
            datasets: [{
                data: [25.3, 18.7, 15.2, 12.8, 10.5, 17.5],
                backgroundColor: ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C', '#C9CDD4'],
                borderWidth: 0,
                hoverOffset: 4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            cutout: '70%',
            onHover: (event, chartElement) => {
                event.native.target.style.cursor = chartElement[0] ? 'pointer' : 'default';
            },
            plugins: {
                legend: { display: false },
                tooltip: {
                    backgroundColor: 'rgba(255, 255, 255, 0.9)',
                    titleColor: '#1D2129',
                    bodyColor: '#4E5969',
                    borderColor: 'rgba(22, 93, 255, 0.2)',
                    borderWidth: 1,
                    padding: 12,
                    boxPadding: 6,
                    usePointStyle: true,
                    callbacks: {
                        label: function (context) {
                            const label = context.label || '';
                            const value = context.parsed || 0;
                            return `${label}: ${value}%`;
                        }
                    }
                }
            },
            animation: {
                animateRotate: true,
                animateScale: true
            }
        }
    });

    document.getElementById('customerTypeChart').onclick = function (evt) {
        const points = customerTypeChart.getElementsAtEventForMode(evt, 'nearest', { intersect: true }, true);
        if (points.length) {
            const firstPoint = points[0];
            const label = customerTypeChart.data.labels[firstPoint.index];
            const typeMap = {
                '重要价值客户': 'vip', '重要保持客户': 'maintain', '重要发展客户': 'develop',
                '重要挽留客户': 'retain', '一般价值客户': 'general', '低价值客户': 'low'
            };
            const type = typeMap[label];
            if (type) {
                showCustomerDetail(type);
            }
        }
    };

    // 客户RFM对比雷达图
    const rfmRadarCtx = document.getElementById('rfmRadarChart').getContext('2d');
    const rfmRadarChart = new Chart(rfmRadarCtx, {
        type: 'radar',
        data: {
            labels: ['最近消费(R)', '消费频率(F)', '消费金额(M)'],
            datasets: [
                {
                    label: '重要价值客户',
                    data: [4.8, 4.5, 4.9],
                    backgroundColor: 'rgba(22, 93, 255, 0.2)',
                    borderColor: '#165DFF',
                    pointBackgroundColor: '#165DFF',
                    pointBorderColor: '#fff',
                    pointHoverBackgroundColor: '#fff',
                    pointHoverBorderColor: '#165DFF'
                },
                {
                    label: '重要保持客户',
                    data: [2.3, 4.2, 4.1],
                    backgroundColor: 'rgba(15, 198, 194, 0.2)',
                    borderColor: '#0FC6C2',
                    pointBackgroundColor: '#0FC6C2',
                    pointBorderColor: '#fff',
                    pointHoverBackgroundColor: '#fff',
                    pointHoverBorderColor: '#0FC6C2'
                },
                {
                    label: '一般价值客户',
                    data: [3.2, 2.8, 2.5],
                    backgroundColor: 'rgba(134, 144, 156, 0.2)',
                    borderColor: '#86909C',
                    pointBackgroundColor: '#86909C',
                    pointBorderColor: '#fff',
                    pointHoverBackgroundColor: '#fff',
                    pointHoverBorderColor: '#86909C'
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                r: {
                    angleLines: { color: 'rgba(0, 0, 0, 0.05)' },
                    grid: { color: 'rgba(0, 0, 0, 0.05)' },
                    pointLabels: { color: '#86909C', font: { size: 12 } },
                    ticks: {
                        backdropColor: 'transparent',
                        color: '#86909C',
                        font: { size: 10 },
                        maxTicksLimit: 5,
                        min: 0,
                        max: 5,
                        stepSize: 1
                    }
                }
            },
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: { boxWidth: 12, padding: 15, color: '#4E5969', font: { size: 12 } }
                },
                tooltip: {
                    backgroundColor: 'rgba(255, 255, 255, 0.9)',
                    titleColor: '#1D2129',
                    bodyColor: '#4E5969',
                    borderColor: 'rgba(22, 93, 255, 0.2)',
                    borderWidth: 1,
                    padding: 12,
                    boxPadding: 6,
                    usePointStyle: true,
                    callbacks: {
                        label: function (context) {
                            return `${context.dataset.label}: ${context.raw}/5分`;
                        }
                    }
                }
            }
        }
    });

    // 客户类型消费贡献度帕累托图
    const customerTypeParetoCtx = document.getElementById('customerTypeParetoChart').getContext('2d');
    const customerTypeParetoChart = new Chart(customerTypeParetoCtx, {
        type: 'bar',
        data: {
            labels: ['重要价值客户', '重要保持客户', '重要发展客户', '重要挽留客户', '一般价值客户', '低价值客户'],
            datasets: [
                {
                    label: '消费金额(万元)',
                    data: [320, 240, 180, 140, 100, 80],
                    backgroundColor: '#165DFF',
                    borderWidth: 0,
                    yAxisID: 'y'
                },
                {
                    label: '累计消费占比',
                    data: [32, 56, 74, 88, 98, 100],
                    borderColor: '#FF7D00',
                    backgroundColor: 'rgba(255, 125, 0, 0.2)',
                    borderWidth: 2,
                    pointBackgroundColor: '#FF7D00',
                    pointRadius: 4,
                    type: 'line',
                    tension: 0.4,
                    yAxisID: 'y1'
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            onHover: (event, chartElement) => {
                const canvas = event.native.target;
                canvas.style.cursor = chartElement[0] ? 'pointer' : 'default';
            },
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: { boxWidth: 12, padding: 15, color: '#4E5969', font: { size: 12 } }
                },
                tooltip: {
                    mode: 'index',
                    intersect: false,
                    backgroundColor: 'rgba(255, 255, 255, 0.9)',
                    titleColor: '#1D2129',
                    bodyColor: '#4E5969',
                    borderColor: 'rgba(22, 93, 255, 0.2)',
                    borderWidth: 1,
                    padding: 12,
                    boxPadding: 6,
                    usePointStyle: true,
                    callbacks: {
                        label: function (context) {
                            if (context.dataset.label === '消费金额(万元)') {
                                return `${context.dataset.label}: ${context.raw}万元`;
                            } else {
                                return `${context.dataset.label}: ${context.raw}%`;
                            }
                        }
                    }
                }
            },
            scales: {
                x: {
                    grid: { display: false },
                    ticks: { color: '#86909C', font: { size: 10 }, autoSkip: false, maxRotation: 45, minRotation: 45 }
                },
                y: {
                    type: 'linear', display: true, position: 'left',
                    title: { display: true, text: '消费金额(万元)', color: '#86909C', font: { size: 12 } },
                    grid: { color: 'rgba(0, 0, 0, 0.05)' },
                    ticks: { color: '#86909C' }
                },
                y1: {
                    type: 'linear', display: true, position: 'right',
                    title: { display: true, text: '累计消费占比(%)', color: '#86909C', font: { size: 12 } },
                    grid: { drawOnChartArea: false },
                    ticks: { color: '#86909C', callback: function (value) { return value + '%'; } },
                    min: 0,
                    max: 100
                }
            }
        }
    });

    // 为帕累托图增加点击穿透
    document.getElementById('customerTypeParetoChart').onclick = function (evt) {
        const points = customerTypeParetoChart.getElementsAtEventForMode(evt, 'nearest', { intersect: true }, true);
        if (points.length) {
            const firstPoint = points[0];
            const label = customerTypeParetoChart.data.labels[firstPoint.index];
            const typeMap = {
                '重要价值客户': 'vip', '重要保持客户': 'maintain', '重要发展客户': 'develop',
                '重要挽留客户': 'retain', '一般价值客户': 'general', '低价值客户': 'low'
            };
            const type = typeMap[label];
            if (type) {
                showCustomerDetail(type);
            }
        }
    };

    // 应用筛选按钮事件
    document.getElementById('applyFilter').addEventListener('click', function () {
        const timeRange = document.getElementById('timeRange').value;
        const region = document.getElementById('region').value;
        const industry = document.getElementById('industry').value;
        const customerType = document.getElementById('customerType').value;

        console.log('应用筛选:', { timeRange, region, industry, customerType });

        const loadingToast = document.createElement('div');
        loadingToast.className = 'fixed bottom-4 right-4 bg-dark text-white px-4 py-2 rounded-lg shadow-lg flex items-center';
        loadingToast.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 数据加载中...';
        document.body.appendChild(loadingToast);

        setTimeout(() => {
            document.body.removeChild(loadingToast);
            const successToast = document.createElement('div');
            successToast.className = 'fixed bottom-4 right-4 bg-success text-white px-4 py-2 rounded-lg shadow-lg flex items-center';
            successToast.innerHTML = '<i class="fa fa-check mr-2"></i> 筛选成功';
            document.body.appendChild(successToast);

            setTimeout(() => {
                document.body.removeChild(successToast);
            }, 2000);
        }, 1000);
    });

    // 重置筛选按钮事件
    document.getElementById('resetFilter').addEventListener('click', function () {
        document.getElementById('timeRange').value = 'month';
        document.getElementById('region').value = 'all';
        document.getElementById('industry').value = 'all';
        document.getElementById('customerType').value = 'all';
    });

    document.getElementById('customerTypeDetailBtn').addEventListener('click', function () {
        showCustomerTypesSummary();
    });

    // 显示KPI指标详情模态框
    window.showKpiDetail = function (kpi) {
        const modal = document.getElementById('detailModal');
        const modalTitle = document.getElementById('modalTitle');
        const modalContent = document.getElementById('modalContent');
        let title = '';
        let content = '';

        switch (kpi) {
            case 'recency':
                title = '平均最近消费天数 (Recency) - 深度分析';
                content = `
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <h4 class="text-md font-medium mb-3">指标解读</h4>
                            <p class="text-sm text-gray-600 leading-relaxed">
                                <b>最近消费天数 (Recency)</b> 反映了客户的活跃状态。该值越小，表示客户最近一次购买行为距离现在越近，活跃度越高，对品牌的记忆和粘性也越强。
                                <br><br>
                                通过分析Recency的分布，我们可以识别出近期活跃的核心客户群体，以及长时间未消费、可能面临流失风险的客户。这为我们制定差异化的营销和关怀策略提供了数据支持。
                            </p>
                        </div>
                        <div class="bg-light rounded-lg p-4">
                            <p class="text-sm text-gray-500 mb-1">客户Recency分布直方图</p>
                            <div class="h-48">
                                <canvas id="recencyDistChart"></canvas>
                            </div>
                        </div>
                    </div>
                `;
                break;
            case 'frequency':
                title = '客均消费频率 (Frequency) - 深度分析';
                content = `
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <h4 class="text-md font-medium mb-3">指标解读</h4>
                            <p class="text-sm text-gray-600 leading-relaxed">
                                <b>消费频率 (Frequency)</b> 指的是客户在特定时间内的购买次数。高频消费的客户通常是品牌的忠实拥护者，他们对企业的价值贡献巨大。
                                <br><br>
                                分析消费频率可以帮助我们识别哪些客户是常客，哪些是偶尔光顾。针对高频客户，我们可以推出VIP计划以增强其忠诚度；对于低频客户，则需要通过精准营销活动来激发其再次购买的兴趣。
                            </p>
                        </div>
                        <div class="bg-light rounded-lg p-4">
                            <p class="text-sm text-gray-500 mb-1">客户Frequency分布直方图</p>
                            <div class="h-48">
                                <canvas id="frequencyDistChart"></canvas>
                            </div>
                        </div>
                    </div>
                `;
                break;
            case 'monetary':
                title = '客均消费金额 (Monetary) - 深度分析';
                content = `
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <h4 class="text-md font-medium mb-3">指标解读</h4>
                            <p class="text-sm text-gray-600 leading-relaxed">
                                <b>消费金额 (Monetary)</b> 是客户在统计周期内的总消费额，直接反映了客户的消费能力和价值贡献。它是衡量客户价值最直接的指标。
                                <br><br>
                                通过分析M值，我们可以筛选出高消费、高价值的“金主”客户，他们是企业利润的主要来源，需要得到最高级别的关注和服务。同时，也可以识别出有提升空间的潜力客户。
                            </p>
                        </div>
                        <div class="bg-light rounded-lg p-4">
                            <p class="text-sm text-gray-500 mb-1">客户Monetary分布直方图</p>
                            <div class="h-48">
                                <canvas id="monetaryDistChart"></canvas>
                            </div>
                        </div>
                    </div>
                `;
                break;
            case 'churn':
                title = '潜在流失客户 - 深度分析';
                content = `
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <h4 class="text-md font-medium mb-3">指标解读</h4>
                            <p class="text-sm text-gray-600 leading-relaxed">
                                <b>潜在流失客户</b> 通常指那些曾经是高价值或中等价值，但近期消费行为显著减少（R值增大）的客户。他们是我们需要重点关注和挽留的对象。
                                <br><br>
                                通过设定预警规则（例如：R > 90天且F > 3次），我们可以主动识别这部分客户，并通过电话回访、专属优惠、情感关怀等方式，在其彻底流失前进行干预，以最低成本实现客户保留。
                            </p>
                        </div>
                         <div class="bg-light rounded-lg p-4">
                            <p class="text-sm text-gray-500 mb-1">流失风险等级分布</p>
                            <div class="h-48">
                                <canvas id="churnRiskChart"></canvas>
                            </div>
                        </div>
                    </div>
                `;
                break;
        }

        modalTitle.textContent = title;
        modalContent.innerHTML = content;
        modal.classList.remove('hidden');

        setTimeout(() => {
            const commonBarOptions = {
                responsive: true, maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: {
                    x: { grid: { display: false }, ticks: { color: '#86909C' } },
                    y: { grid: { color: 'rgba(0,0,0,0.05)' }, ticks: { color: '#86909C' } }
                }
            };

            if (kpi === 'recency') {
                const ctx = document.getElementById('recencyDistChart').getContext('2d');
                new Chart(ctx, {
                    type: 'bar',
                    data: {
                        labels: ['0-15天', '16-30天', '31-60天', '61-90天', '>90天'],
                        datasets: [{ label: '客户数', data: [1200, 2500, 800, 350, 150], backgroundColor: '#165DFF' }]
                    },
                    options: { ...commonBarOptions, scales: { ...commonBarOptions.scales, x: { ...commonBarOptions.scales.x, title: { display: true, text: '最近消费天数' } } } }
                });
            } else if (kpi === 'frequency') {
                const ctx = document.getElementById('frequencyDistChart').getContext('2d');
                new Chart(ctx, {
                    type: 'bar',
                    data: {
                        labels: ['1-2次', '3-5次', '6-10次', '11-20次', '>20次'],
                        datasets: [{ label: '客户数', data: [2800, 1500, 500, 150, 50], backgroundColor: '#0FC6C2' }]
                    },
                    options: { ...commonBarOptions, scales: { ...commonBarOptions.scales, x: { ...commonBarOptions.scales.x, title: { display: true, text: '消费频次' } } } }
                });
            } else if (kpi === 'monetary') {
                const ctx = document.getElementById('monetaryDistChart').getContext('2d');
                new Chart(ctx, {
                    type: 'bar',
                    data: {
                        labels: ['<1k', '1k-5k', '5k-1w', '1w-5w', '>5w'],
                        datasets: [{ label: '客户数', data: [1100, 2300, 900, 600, 100], backgroundColor: '#FF7D00' }]
                    },
                    options: { ...commonBarOptions, scales: { ...commonBarOptions.scales, x: { ...commonBarOptions.scales.x, title: { display: true, text: '消费金额(元)' } } } }
                });
            } else if (kpi === 'churn') {
                const ctx = document.getElementById('churnRiskChart').getContext('2d');
                new Chart(ctx, {
                    type: 'doughnut',
                    data: {
                        labels: ['高风险', '中风险', '低风险'],
                        datasets: [{ data: [128, 118, 80], backgroundColor: ['#F53F3F', '#FF7D00', '#86909C'] }]
                    },
                    options: {
                        responsive: true, maintainAspectRatio: false, cutout: '60%',
                        plugins: { legend: { position: 'right' } }
                    }
                });
            }
        }, 100);
    };

    window.showTrendDetail = function (month, avgScore) {
        const modal = document.getElementById('detailModal');
        const modalTitle = document.getElementById('modalTitle');
        const modalContent = document.getElementById('modalContent');

        modalTitle.textContent = `${month} - RFM总分趋势详情`;
        modalContent.innerHTML = `
            <div class="mb-4">
                <p class="text-sm text-gray-600">
                    <b>${month}</b> 的RFM总分平均值为 <b>${avgScore}</b>。以下是该月每日的RFM分数明细，展现了客户价值的短期波动情况。
                </p>
            </div>
            <h4 class="text-md font-medium mb-3">每日RFM分数明细 (模拟数据)</h4>
            <div class="overflow-y-auto max-h-96">
                <table class="w-full">
                    <thead>
                        <tr class="border-b border-gray-200">
                            <th class="text-left py-2 px-2 text-sm font-medium text-gray-600">日期</th>
                            <th class="text-center py-2 px-2 text-sm font-medium text-gray-600">RFM平均分</th>
                            <th class="text-center py-2 px-2 text-sm font-medium text-gray-600">日变化</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${Array.from({ length: 30 }, (_, i) => `
                        <tr class="border-b border-gray-100 hover:bg-gray-50">
                            <td class="py-2 px-2 text-sm font-medium">${month.replace('月', '')}月${i + 1}日</td>
                            <td class="py-2 px-2 text-sm text-center">${(avgScore - 0.5 + Math.random()).toFixed(2)}</td>
                            <td class="py-2 px-2 text-sm text-center">${(Math.random() > 0.5 ? '<span class="text-success">↑</span>' : '<span class="text-danger">↓</span>')} ${(Math.random() * 0.5).toFixed(2)}</td>
                        </tr>
                        `).join('')}
                    </tbody>
                </table>
            </div>
        `;

        modal.classList.remove('hidden');
    };

    window.showCustomerTypesSummary = function () {
        const modal = document.getElementById('detailModal');
        const modalTitle = document.getElementById('modalTitle');
        const modalContent = document.getElementById('modalContent');

        modalTitle.textContent = '客户类型定义与分析';
        modalContent.innerHTML = `
            <div class="space-y-4">
                <div>
                    <h4 class="text-md font-medium text-primary">重要价值客户 (VIP)</h4>
                    <p class="text-sm text-gray-600"><b>特征</b>: R、F、M三项得分都很高。他们是消费频率高、消费金额大、最近有消费的顶级客户。<br><b>策略</b>: 提供VIP服务，专属客户经理，个性化关怀，保持其高忠诚度。</p>
                </div>
                <div>
                    <h4 class="text-md font-medium text-secondary">重要保持客户</h4>
                    <p class="text-sm text-gray-600"><b>特征</b>: 最近有消费(R高)，消费频率和金额(F/M)也很高，但可能略逊于VIP客户。<br><b>策略</b>: 重点保持，通过交叉销售、向上销售提升其价值，防止其流向竞争对手。</p>
                </div>
                <div>
                    <h4 class="text-md font-medium text-warning">重要发展客户</h4>
                    <p class="text-sm text-gray-600"><b>特征</b>: 最近有消费(R高)，但消费频率或金额(F/M)不高。他们是潜力股。<br><b>策略</b>: 开展精准营销，通过促销、捆绑销售等方式，刺激其提高消费频率和单价。</p>
                </div>
                <div>
                    <h4 class="text-md font-medium text-danger">重要挽留客户</h4>
                    <p class="text-sm text-gray-600"><b>特征</b>: 曾经是高价值客户(F/M高)，但很久没消费了(R低)。流失风险极高。<br><b>策略</b>: 立即采取挽留措施，通过电话回访、发送召回优惠券等方式主动联系，唤醒客户。</p>
                </div>
                <div>
                    <h4 class="text-md font-medium text-info">一般价值客户</h4>
                    <p class="text-sm text-gray-600"><b>特征</b>:各项RFM指标表现平平。是客户群中的大多数。<br><b>策略</b>: 维持基本服务，通过自动化营销手段，尝试筛选出其中具有提升潜力的个体。</p>
                </div>
                 <div>
                    <h4 class="text-md font-medium" style="color: #C9CDD4;">低价值客户</h4>
                    <p class="text-sm text-gray-600"><b>特征</b>:各项RFM指标得分都很低。<br><b>策略</b>: 无需投入过多资源，维持品牌曝光即可，避免打扰。</p>
                </div>
            </div>
        `;

        modal.classList.remove('hidden');
    };

    // 显示客户详情模态框
    window.showCustomerDetail = function (type) {
        const modal = document.getElementById('detailModal');
        const modalTitle = document.getElementById('modalTitle');
        const modalContent = document.getElementById('modalContent');

        let title = '';
        let content = '';

        switch (type) {
            case 'vip':
                title = '重要价值客户详情';
                content = `
          <div class="mb-6">
            <h4 class="text-md font-medium mb-3">客户分布</h4>
            <div class="grid grid-cols-2 gap-4">
              <div class="bg-light rounded-lg p-4">
                <p class="text-sm text-gray-500 mb-1">地区分布</p>
                <div class="h-40">
                  <canvas id="vipRegionChart"></canvas>
                </div>
              </div>
              <div class="bg-light rounded-lg p-4">
                <p class="text-sm text-gray-500 mb-1">行业分布</p>
                <div class="h-40">
                  <canvas id="vipIndustryChart"></canvas>
                </div>
              </div>
            </div>
          </div>

          <h4 class="text-md font-medium mb-3">客户列表</h4>
          <div class="overflow-x-auto">
            <table class="w-full">
              <thead>
                <tr class="border-b border-gray-200">
                  <th class="text-left py-2 px-2 text-sm font-medium text-gray-600">客户名称</th>
                  <th class="text-center py-2 px-2 text-sm font-medium text-gray-600">最近消费</th>
                  <th class="text-center py-2 px-2 text-sm font-medium text-gray-600">消费频率</th>
                  <th class="text-center py-2 px-2 text-sm font-medium text-gray-600">消费金额</th>
                  <th class="text-center py-2 px-2 text-sm font-medium text-gray-600">RFM评分</th>
                  <th class="text-center py-2 px-2 text-sm font-medium text-gray-600">操作</th>
                </tr>
              </thead>
              <tbody>
                <tr class="border-b border-gray-100 hover:bg-gray-50">
                  <td class="py-2 px-2 text-sm font-medium">恒业科技有限公司</td>
                  <td class="py-2 px-2 text-sm text-center">2025-06-18</td>
                  <td class="py-2 px-2 text-sm text-center">12次/月</td>
                  <td class="py-2 px-2 text-sm text-center">¥286,500</td>
                  <td class="py-2 px-2 text-sm text-center">R5F5M5</td>
                  <td class="py-2 px-2 text-sm text-center">
                    <button class="text-primary hover:text-primary/80">
                      详情
                    </button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        `;
                break;
            case 'maintain':
                title = '重要保持客户详情';
                content = `
          <div class="mb-6">
            <h4 class="text-md font-medium mb-3">客户特征分析</h4>
            <div class="bg-light rounded-lg p-4">
              <div class="h-64">
                <canvas id="maintainFeatureChart"></canvas>
              </div>
            </div>
          </div>

          <h4 class="text-md font-medium mb-3">客户列表</h4>
          <div class="overflow-x-auto">
            <table class="w-full">
              <thead>
                <tr class="border-b border-gray-200">
                  <th class="text-left py-2 px-2 text-sm font-medium text-gray-600">客户名称</th>
                  <th class="text-center py-2 px-2 text-sm font-medium text-gray-600">最近消费</th>
                  <th class="text-center py-2 px-2 text-sm font-medium text-gray-600">消费频率</th>
                  <th class="text-center py-2 px-2 text-sm font-medium text-gray-600">消费金额</th>
                  <th class="text-center py-2 px-2 text-sm font-medium text-gray-600">RFM评分</th>
                  <th class="text-center py-2 px-2 text-sm font-medium text-gray-600">操作</th>
                </tr>
              </thead>
              <tbody>
                <tr class="border-b border-gray-100 hover:bg-gray-50">
                  <td class="py-2 px-2 text-sm font-medium">创新电子有限公司</td>
                  <td class="py-2 px-2 text-sm text-center">2025-06-08</td>
                  <td class="py-2 px-2 text-sm text-center">6次/月</td>
                  <td class="py-2 px-2 text-sm text-center">¥156,800</td>
                  <td class="py-2 px-2 text-sm text-center">R3F3M4</td>
                  <td class="py-2 px-2 text-sm text-center">
                    <button class="text-primary hover:text-primary/80">
                      详情
                    </button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        `;
                break;
            case 'develop':
                title = '重要发展客户详情';
                content = `<p class="text-center p-8">重要发展客户是指消费频率和金额不高，但最近有消费行为（R值较高）的客户。他们具备转化为高价值客户的潜力，需要通过精准营销和产品推荐来提升其消费频率和金额。详细列表和分析功能正在开发中...</p>`;
                break;
            case 'retain':
                title = '重要挽留客户详情';
                content = `<p class="text-center p-8">重要挽留客户是指最近消费时间较远，但曾经消费频率或金额较高（F/M值较高）的客户。他们是流失风险极高的价值客户，需要立即采取措施进行关怀和挽留。详细列表和分析功能正在开发中...</p>`;
                break;
            case 'general':
                title = '一般价值客户详情';
                content = `<p class="text-center p-8">一般价值客户的各项RFM指标表现平平，是客户群中的大多数。对这部分客户可以维持基本的服务，并通过自动化营销手段，尝试筛选出其中具有提升潜力的个体。详细列表和分析功能正在开发中...</p>`;
                break;
            case 'low':
                title = '低价值客户详情';
                content = `<p class="text-center p-8">低价值客户在所有RFM维度上得分都很低，他们可能是新客户、一次性客户或即将流失的客户。对这部分客户无需投入过多资源，维持品牌曝光即可。详细列表和分析功能正在开发中...</p>`;
                break;
            default:
                title = '客户详情';
                content = '<p>暂无数据</p>';
        }

        modalTitle.textContent = title;
        modalContent.innerHTML = content;
        modal.classList.remove('hidden');

        if (type === 'vip') {
            setTimeout(() => {
                const vipRegionCtx = document.getElementById('vipRegionChart').getContext('2d');
                new Chart(vipRegionCtx, {
                    type: 'pie',
                    data: {
                        labels: ['华东', '华南', '华北', '西北', '华中'],
                        datasets: [{
                            data: [45, 25, 15, 8, 7],
                            backgroundColor: ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C'],
                            borderWidth: 0
                        }]
                    },
                    options: {
                        responsive: true, maintainAspectRatio: false,
                        plugins: {
                            legend: { position: 'right', labels: { boxWidth: 12, padding: 10, color: '#4E5969', font: { size: 10 } } },
                            tooltip: { backgroundColor: 'rgba(255, 255, 255, 0.9)', titleColor: '#1D2129', bodyColor: '#4E5969', borderColor: 'rgba(22, 93, 255, 0.2)', borderWidth: 1, padding: 10, boxPadding: 4, usePointStyle: true }
                        }
                    }
                });

                const vipIndustryCtx = document.getElementById('vipIndustryChart').getContext('2d');
                new Chart(vipIndustryCtx, {
                    type: 'pie',
                    data: {
                        labels: ['科技', '金融', '制造', '零售', '服务'],
                        datasets: [{
                            data: [35, 20, 18, 15, 12],
                            backgroundColor: ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C'],
                            borderWidth: 0
                        }]
                    },
                    options: {
                        responsive: true, maintainAspectRatio: false,
                        plugins: {
                            legend: { position: 'right', labels: { boxWidth: 12, padding: 10, color: '#4E5969', font: { size: 10 } } },
                            tooltip: { backgroundColor: 'rgba(255, 255, 255, 0.9)', titleColor: '#1D2129', bodyColor: '#4E5969', borderColor: 'rgba(22, 93, 255, 0.2)', borderWidth: 1, padding: 10, boxPadding: 4, usePointStyle: true }
                        }
                    }
                });
            }, 100);
        }

        if (type === 'maintain') {
            setTimeout(() => {
                const maintainFeatureCtx = document.getElementById('maintainFeatureChart').getContext('2d');
                new Chart(maintainFeatureCtx, {
                    type: 'radar',
                    data: {
                        labels: ['最近消费(R)', '消费频率(F)', '消费金额(M)', '客户忠诚度', '产品偏好度', '推荐指数'],
                        datasets: [
                            {
                                label: '重要保持客户',
                                data: [2.3, 4.2, 4.1, 3.8, 3.5, 3.9],
                                backgroundColor: 'rgba(15, 198, 194, 0.2)',
                                borderColor: '#0FC6C2',
                                pointBackgroundColor: '#0FC6C2',
                                pointBorderColor: '#fff',
                                pointHoverBackgroundColor: '#fff',
                                pointHoverBorderColor: '#0FC6C2'
                            },
                            {
                                label: '重要价值客户',
                                data: [4.8, 4.5, 4.9, 4.7, 4.5, 4.8],
                                backgroundColor: 'rgba(22, 93, 255, 0.1)',
                                borderColor: '#165DFF',
                                pointBackgroundColor: '#165DFF',
                                pointBorderColor: '#fff',
                                pointHoverBackgroundColor: '#fff',
                                pointHoverBorderColor: '#165DFF'
                            }
                        ]
                    },
                    options: {
                        responsive: true, maintainAspectRatio: false,
                        scales: {
                            r: {
                                angleLines: { color: 'rgba(0, 0, 0, 0.05)' },
                                grid: { color: 'rgba(0, 0, 0, 0.05)' },
                                pointLabels: { color: '#86909C', font: { size: 11 } },
                                ticks: { backdropColor: 'transparent', color: '#86909C', font: { size: 9 }, maxTicksLimit: 5, min: 0, max: 5, stepSize: 1 }
                            }
                        },
                        plugins: {
                            legend: { position: 'bottom', labels: { boxWidth: 12, padding: 15, color: '#4E5969', font: { size: 11 } } },
                            tooltip: {
                                backgroundColor: 'rgba(255, 255, 255, 0.9)', titleColor: '#1D2129', bodyColor: '#4E5969', borderColor: 'rgba(22, 93, 255, 0.2)', borderWidth: 1, padding: 10, boxPadding: 4, usePointStyle: true,
                                callbacks: {
                                    label: function (context) {
                                        return `${context.dataset.label}: ${context.raw}/5分`;
                                    }
                                }
                            }
                        }
                    }
                });
            }, 100);
        }
    };

    // 关闭模态框
    document.getElementById('closeModal').addEventListener('click', function () {
        document.getElementById('detailModal').classList.add('hidden');
    });
    document.getElementById('closeModalBtn').addEventListener('click', function () {
        document.getElementById('detailModal').classList.add('hidden');
    });
    document.getElementById('detailModal').addEventListener('click', function (e) {
        if (e.target === this) {
            this.classList.add('hidden');
        }
    });

    // 为热力图添加tooltip效果
    document.querySelectorAll('.tooltip').forEach(el => {
        el.addEventListener('mouseover', function (e) {
            const tooltip = document.createElement('div');
            tooltip.className = 'absolute bg-dark text-white text-xs px-2 py-1 rounded shadow-lg z-10';
            tooltip.textContent = this.dataset.tooltip;
            tooltip.style.left = `${e.pageX - 50}px`;
            tooltip.style.top = `${e.pageY - 30}px`;
            document.body.appendChild(tooltip);
            this.tooltip = tooltip;
        });
        el.addEventListener('mouseout', function () {
            if (this.tooltip) {
                document.body.removeChild(this.tooltip);
                delete this.tooltip;
            }
        });
    });
});